package com.hclc.yxb.util;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hclc.entity.dvo.MenuTreeDvo;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/9/26.
 */
public class MenuTreeToolUtils {

    private List<MenuTreeDvo> rootList; //根节点对象存放到这里

    private List<MenuTreeDvo> bodyList; //其他节点存放到这里，可以包含根节点

    public MenuTreeToolUtils(List<MenuTreeDvo> rootList, List<MenuTreeDvo> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    public List<MenuTreeDvo> getTree() {   //调用的方法入口
        if (bodyList != null && !bodyList.isEmpty()) {
            //声明一个map，用来过滤已操作过的数据
            Map<String, String> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree, map));//传递根对象和一个空map
            return rootList;
        }
        return null;
    }

    public void getChild(MenuTreeDvo beanTree, Map<String, String> map) {
        List<MenuTreeDvo> childList = Lists.newArrayList();
        bodyList.stream()
                .filter(c -> !map.containsKey(c.getId()))//map内不包含子节点的code
                .filter(c -> c.getParentId().equals(beanTree.getId()))//子节点的父id==根节点的code 继续循环
                .forEach(c -> {
                    map.put(c.getId(), c.getParentId());//当前节点code和父节点id
                    getChild(c, map);//递归调用
                    childList.add(c);
                });
        beanTree.setChildren(childList);
        if (CollectionUtils.isEmpty(childList)) {
            beanTree.setChildren(null);
        }
    }
}
